package com.yuanheng100.ems4j.web.interceptor;

import com.yuanheng100.ems4j.web.manager.SessionManager;
import org.slf4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.lang.reflect.Method;

/**
 * 方法拦截器
 * Created by wangguangshuo on 2017/1/18.
 */
@Aspect
@Component
public class MethodInterceptor
{
    private Logger logger = LoggerFactory.getLogger(MethodInterceptor.class);

    @Autowired
    private SessionManager sessionManager;

    @Pointcut("execution(* com.yuanheng100.ems4j.web.controller.session.*Controller.*(..))")
    private void loginSession() {};


    /*用户登录验证拦截，要求所有被验证的方法第一个参数都要是HttpServletResponse，如果不是则方法不会被拦截*/
    @Around("loginSession()&&args(response,..)")
    public Object doLoginSession(ProceedingJoinPoint pjp, HttpServletResponse response) throws Throwable {
        if (sessionManager != null && sessionManager.getEms4jEmployee() != null) {
            Signature sig = pjp.getSignature();
            MethodSignature msig = (MethodSignature) sig;
            Object target = pjp.getTarget();
            Method currentMethod = target.getClass().getMethod(msig.getName(), msig.getParameterTypes());
            logger.info("用户（"+sessionManager.getEms4jEmployee().getName()+"）操作方法："+currentMethod.getName());
            return  pjp.proceed();
        } else {
            logger.info("用户未登录或登录失效");
            response.setContentType("text/html");
            response.setCharacterEncoding("GBK");
            PrintWriter out = response.getWriter();
            out.print("nologin");
            out.flush();
            out.close();
            return null;
        }
    }
}
